<template>
  <view class="admin-logs-page">
    <view class="page-header">
      <view class="header-left">
        <view class="back-btn" @click="navigateBack">
          <view class="icon icon-arrow-left" style="font-size: 20px;">‹</view>
          <text class="header-title">操作日志</text>
        </view>
      </view>
    </view>
    
    <!-- 搜索和筛选区域 -->
    <view class="filter-area">
      <view class="search-box">
        <view class="icon icon-search" style="font-size: 16px;">🔍</view>
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索操作内容或目标"
          class="search-input"
          @input="onSearch"
        />
      </view>
      
      <view class="filter-actions">
         <picker 
            :range="actionOptions"
            mode="selector" 
          @change="onActionChange"
        >
          <button class="filter-btn" size="mini" type="default">
            {{ actionOptions[selectedActionIndex] || '全部操作' }}
          </button>
        </picker>
        
        <button class="filter-btn" size="mini" type="default" @click="clearFilters">
          清空筛选
        </button>
      </view>
    </view>
    
    <!-- 日志列表 -->
    <view class="logs-list" v-if="!isLoading">
      <view 
        v-for="log in logs" 
        :key="log._id"
        class="log-item"
      >
        <view class="log-header">
          <text class="log-admin">{{ log.admin_name }}</text>
          <text class="log-time">{{ formatDateTime(log.create_time) }}</text>
        </view>
        <view class="log-content">
          <text class="log-action">操作类型: {{ getActionText(log.action) }}</text>
          <text v-if="log.target_name" class="log-target">目标: {{ log.target_name }}</text>
          <text v-if="log.message" class="log-message">{{ log.message }}</text>
        </view>
        <view v-if="log.changes" class="log-changes">
          <text class="changes-title">变更内容:</text>
          <text 
            v-for="(value, key) in log.changes" 
            :key="key"
            class="change-item"
          >
            {{ getFieldName(key) }}: {{ value }}
          </text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="logs.length === 0" class="empty-state">
        <view class="icon icon-empty" style="font-size: 48px;">📝</view>
        <text class="empty-text">暂无日志数据</text>
      </view>
    </view>
    
    <!-- 加载中状态 -->
    <view v-else class="loading-state">
      <view class="icon icon-loading" style="font-size: 48px;">⏳</view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore && !isLoading" class="load-more">
      <button class="load-more-btn" @click="loadMoreLogs">加载更多</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import {onLoad} from "@dcloudio/uni-app"

// 状态管理
const logs = ref([]);
const searchKeyword = ref('');
const selectedActionIndex = ref(0);
const isLoading = ref(true);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(20);

// 操作选项
const actionOptions = ref([
  '全部操作',
  'get_wallpaper_detail',
  'update_wallpaper',
  'delete_wallpaper',
  'add_wallpaper',
  'get_category_detail',
  'update_category',
  'delete_category',
  'add_category',
  'get_users',
  'delete_user',
  'update_feedback_status'
]);

// 字段名称映射
const fieldNames = {
  title: '标题',
  categoryId: '分类ID',
  description: '描述',
  name: '名称',
  icon: '图标',
  status: '状态'
};

// 生命周期
onLoad(() => {
  // 移除管理员权限校验
  loadLogs();
});

// 管理员权限校验已移除

// 加载日志
const loadLogs = async (isLoadMore = false) => {
  if (isLoading.value) return;
  
  try {
    isLoading.value = true;
    
    const action = selectedActionIndex.value > 0 ? actionOptions.value[selectedActionIndex.value] : '';
    
    const result = await uniCloud.callFunction({
      name: 'admingetAdminLogs',
      data: {
        page: isLoadMore ? page.value : 1,
        pageSize: pageSize.value,
        keyword: searchKeyword.value.trim(),
        action: action
      }
    });
    
    if (result && result.result && result.result.code === 0) {
      const newLogs = result.result.data || [];
      
      if (isLoadMore) {
        logs.value = [...logs.value, ...newLogs];
      } else {
        logs.value = newLogs;
        page.value = 1;
      }
      
      hasMore.value = newLogs.length === pageSize.value;
      
      if (isLoadMore && hasMore.value) {
        page.value++;
      }
    } else {
      uni.showToast({ 
        title: result.result?.message || '加载日志失败', 
        icon: 'none' 
      });
      // 使用模拟数据
      if (!isLoadMore) {
        mockLogs();
      }
    }
  } catch (error) {
    console.error('加载日志失败:', error);
    // 使用模拟数据
    if (!isLoadMore) {
      mockLogs();
    }
  } finally {
    isLoading.value = false;
  }
};

// 模拟日志数据
const mockLogs = () => {
  logs.value = [
    {
      _id: 'log1',
      admin_id: 'admin1',
      admin_name: 'admin',
      action: 'update_wallpaper',
      target_id: 'wallpaper1',
      target_title: '测试壁纸',
      changes: {
        title: '更新后的壁纸标题',
        categoryId: '2'
      },
      create_time: Date.now() - 3600000
    },
    {
      _id: 'log2',
      admin_id: 'admin1',
      admin_name: 'admin',
      action: 'add_wallpaper',
      target_id: 'wallpaper2',
      target_title: '新增壁纸',
      message: '成功添加新壁纸',
      create_time: Date.now() - 7200000
    },
    {
      _id: 'log3',
      admin_id: 'admin1',
      admin_name: 'admin',
      action: 'delete_wallpaper',
      target_id: 'wallpaper3',
      target_title: '要删除的壁纸',
      create_time: Date.now() - 10800000
    }
  ];
  hasMore.value = false;
};

// 格式化日期时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 获取操作文本
const getActionText = (action) => {
  const actionMap = {
    'get_wallpaper_detail': '查看壁纸详情',
    'update_wallpaper': '更新壁纸',
    'delete_wallpaper': '删除壁纸',
    'add_wallpaper': '添加壁纸',
    'get_category_detail': '查看分类详情',
    'update_category': '更新分类',
    'delete_category': '删除分类',
    'add_category': '添加分类',
    'get_users': '获取用户列表',
    'delete_user': '删除用户',
    'update_feedback_status': '更新反馈状态'
  };
  return actionMap[action] || action;
};

// 获取字段名称
const getFieldName = (field) => {
  return fieldNames[field] || field;
};

// 搜索日志
const onSearch = () => {
  clearTimeout(window.searchTimer);
  window.searchTimer = setTimeout(() => {
    loadLogs();
  }, 300);
};

// 操作类型筛选
const onActionChange = (e) => {
  selectedActionIndex.value = e.detail.value;
  loadLogs();
};

// 清空筛选条件
const clearFilters = () => {
  searchKeyword.value = '';
  selectedActionIndex.value = 0;
  loadLogs();
};

// 加载更多日志
const loadMoreLogs = () => {
  if (hasMore.value && !isLoading.value) {
    loadLogs(true);
  }
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style scoped lang="less">
.icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.admin-logs-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .header-left {
      .back-btn {
        display: flex;
        align-items: center;
        
        .header-title {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-left: 4px;
        }
      }
    }
  }
  
  .filter-area {
    padding: 16px;
    background-color: #fff;
    
    .search-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 8px;
      padding: 0 12px;
      height: 40px;
      margin-bottom: 12px;
      
      .search-input {
        flex: 1;
        margin-left: 8px;
        font-size: 14px;
        height: 100%;
      }
    }
    
    .filter-actions {
      display: flex;
      gap: 8px;
    }
    
    .filter-btn {
      font-size: 14px;
    }
  }
  
  .logs-list {
    padding: 16px;
    
    .log-item {
      background-color: #fff;
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      
      .log-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        
        .log-admin {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
        
        .log-time {
          font-size: 12px;
          color: #999;
        }
      }
      
      .log-content {
        margin-bottom: 8px;
        
        .log-action,
        .log-target,
        .log-message {
          display: block;
          font-size: 14px;
          color: #666;
          margin-bottom: 4px;
        }
      }
      
      .log-changes {
        background-color: #f9f9f9;
        padding: 8px 12px;
        border-radius: 6px;
        
        .changes-title {
          display: block;
          font-size: 12px;
          color: #999;
          margin-bottom: 4px;
          font-weight: 500;
        }
        
        .change-item {
          display: block;
          font-size: 12px;
          color: #666;
          margin-bottom: 2px;
        }
      }
    }
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 64px 0;
      
      .empty-text {
        font-size: 14px;
        color: #666;
        margin-top: 16px;
      }
    }
  }
  
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 64px 0;
    
    .loading-text {
      font-size: 14px;
      color: #666;
      margin-top: 16px;
    }
  }
  
  .load-more {
    padding: 16px;
    text-align: center;
    
    .load-more-btn {
      font-size: 14px;
      color: #007aff;
      background-color: transparent;
    }
  }
}
</style>